package com.fishery.quartz.service;

import com.fishery.quartz.entity.Task;
import com.fishery.quartz.task.ExecuteTask;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * 任务调度管理器
 */
@Component
public class QuartzManager {

	@Autowired
	@Qualifier("myScheduler")
	private Scheduler scheduler;


	/**
	 * 添加任务
	 *
	 * @param task
	 */
	public void add(Task task) {
		try {
			// 定义任务，创建JobDetail实例，用于绑定Job实现类
			JobDetail jobDetail = JobBuilder.newJob(ExecuteTask.class)
					.withIdentity(task.getJobName(), task.getJobGroup())
					.usingJobData("requestMethod", task.getRequestMethod())
					.usingJobData("requestUri", task.getRequestUri())
					.usingJobData("requestBody", task.getRequestBody()).build();
			// 定义触发器，采用cronTrigger规则
			Trigger trigger = TriggerBuilder.newTrigger().withIdentity(task.getJobName(), task.getJobGroup())
					.startAt(DateBuilder.futureDate(1, DateBuilder.IntervalUnit.SECOND))
					.withSchedule(CronScheduleBuilder.cronSchedule(task.getCronExpression())
							.withMisfireHandlingInstructionDoNothing()).build();
			// 将任务和触发器放到任务调度中
			scheduler.scheduleJob(jobDetail, trigger);
			if (task.getJobStatus().equals("0")) {
				pause(task.getJobName(), task.getJobGroup());
			}
			// 启动
			if (scheduler.isShutdown()) {
				scheduler.start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 暂停任务
	 *
	 * @param jobName
	 * @param jobGroup
	 */
	public void pause(String jobName, String jobGroup) {
		try {
			scheduler.pauseJob(JobKey.jobKey(jobName, jobGroup));
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 恢复任务
	 *
	 * @param jobName
	 * @param jobGroup
	 */
	public void resume(String jobName, String jobGroup) {
		try {
			scheduler.resumeJob(JobKey.jobKey(jobName, jobGroup));
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除任务
	 *
	 * @param jobName
	 * @param jobGroup
	 */
	public void delete(String jobName, String jobGroup) {
		try {
			scheduler.deleteJob(JobKey.jobKey(jobName, jobGroup));
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 修改cron表达式
	 *
	 * @param jobName
	 * @param jobGroup
	 * @param cronExpression
	 */
	public void update(String jobName, String jobGroup, String cronExpression) {
		try {
			TriggerKey triggerKey = TriggerKey.triggerKey(jobName, jobGroup);
			CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
			trigger.getTriggerBuilder().withIdentity(triggerKey).
					withSchedule(CronScheduleBuilder.cronSchedule(cronExpression)
							.withMisfireHandlingInstructionDoNothing()).build();
			scheduler.rescheduleJob(triggerKey, trigger);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

}
